//
//  SwitchView.swift
//  AmountBody
//
//  Created by Qiu Jishuai on 2018/1/25.
//  Copyright © 2018年 RCMTM. All rights reserved.
//

import UIKit
import Masonry

class SwitchView: UIView {

    var itemSpacing: CGFloat = 15
    var leadSpacing: CGFloat = 10
    var tailSpacing: CGFloat = 10

    var itemWidth: CGFloat = 60
    //如果设置了该属性 button及vernier的宽度将由文字宽度决定,且不能设置view的width约束
    var autoresizesWithTitle: Bool = true

    var itemFont: UIFont = .systemFont(ofSize: 14)
    var selectedThemeColor: UIColor = UIColor(hexString: "#ff4259")!
    var themeColor: UIColor = UIColor(hexString: "#9b9b9b")!
    var vernierHeight: CGFloat = 2

    var indexChangedAction: ((Int) -> Void)?

    let vernier = UIView()

    private(set) var buttons: [UIButton] = []
    private(set) var index: Int = 0

    func setIndex(_ index: Int, animated: Bool) {
        setIndex(index, animated: animated, notifyObserver: false)
    }

    var titles: [String] = [] {
        didSet {
            if titles == oldValue { return }
            let count = titles.count

            if count == 0 {
                return
            }
            vernier.backgroundColor = selectedThemeColor

            while buttons.count < count {
                let button = UIButton()
                addSubview(button)
                button.setTitleColor(themeColor, for: .normal)
                button.setTitleColor(selectedThemeColor, for: .disabled)
                buttons.append(button)
                button.titleLabel?.font = itemFont
                button.addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)
            }

            while buttons.count > count {
                buttons.removeLast().removeFromSuperview()
            }

            for (i, title) in titles.enumerated() {
                let button = buttons[i]
                button.tag = i
                button.setTitle(title, for: .normal)
                if (autoresizesWithTitle) {
                     button.sizeToFit()
                }

                button.mas_remakeConstraints({ (make) in
                    if i == 0 {
                        make?.left.equalTo()(self)?.offset()(leadSpacing + itemSpacing)
                    } else {
                        make?.left.equalTo()(buttons[i - 1].mas_right)?.offset()(itemSpacing)
                    }
                    if i == count - 1 {
                        make?.right.equalTo()(self)?.offset()(-tailSpacing)
                    }
                    if (autoresizesWithTitle) {
                        make?.width.equalTo()(button.width)
                    } else {
                        make?.width.equalTo()(itemWidth)?.priority()(MASLayoutPriorityDefaultMedium)
                    }
                    make?.top.equalTo()(self)
                    make?.bottom.equalTo()(self)?.offset()(-3)
                })
            }
            vernier.mas_remakeConstraints { (make) in
                make?.height.equalTo()(vernierHeight)
                make?.width.equalTo()(buttons[index])
                make?.centerX.equalTo()(buttons[index])
                make?.bottom.equalTo()(self)
            }
            setIndex(index > titles.count - 1 ? 0 : index, animated: false)
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    private func setup() {
        backgroundColor = UIColor.white
        addSubview(vernier)
    }

    @objc private func buttonClicked(_ sender: UIButton) {
        setIndex(sender.tag, animated: true, notifyObserver: true)
    }

    private func setIndex(_ index: Int, animated: Bool, notifyObserver: Bool) {
        self.buttons.forEach({ (button) in
            button.isEnabled = true
        })
        let button = self.buttons[index]
        button.isEnabled = false
        vernier.mas_remakeConstraints { (make) in
            make?.height.equalTo()(self.vernierHeight)
            make?.width.equalTo()(button)
            make?.centerX.equalTo()(button)
            make?.bottom.equalTo()(self)
        }
        self.index = index

        if animated {
            UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: {
                self.layoutIfNeeded()
            }, completion: { _ in
                if notifyObserver {
                   self.indexChangedAction?(index)
                }
            })
        } else {
            layoutIfNeeded()
            if notifyObserver {
                indexChangedAction?(index)
            }
        }
    }
}
